﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;

namespace InventoryManager
{
    public partial class ViewRequisitionForm_1_UserControl : UserControl
    {
        public event FormChangedHandler FormChangedEvent;

        private string _connectionString;
        private MySqlConnection _connection;
        private MySqlDataAdapter _mySqlDataAdapter;

        private const string COLUMN_1_NAME = "เคยทำใบกำกับภาษี";
        private const string COLUMN_2_NAME = "เลขที่";
        private const string COLUMN_3_NAME = "ผู้ซื้อ";
        private const string COLUMN_4_NAME = "วันที่";

        private bool _invoiceMode;

        public ViewRequisitionForm_1_UserControl(string connectionString, int width, int height, bool invoiceMode)
        {
            InitializeComponent();

            RecentlyAddedButton_1.SoftButton_1.Click += new EventHandler(ViewReportButton_1_Click);
            RecentlyAddedButton_1.SoftButton_2.Click += new EventHandler(EditReportButton_1_Click);
            RecentlyAddedButton_2.SoftButton_1.Click += new EventHandler(ViewReportButton_2_Click);
            RecentlyAddedButton_2.SoftButton_2.Click += new EventHandler(EditReportButton_2_Click);
            RecentlyAddedButton_3.SoftButton_1.Click += new EventHandler(ViewReportButton_3_Click);
            RecentlyAddedButton_3.SoftButton_2.Click += new EventHandler(EditReportButton_3_Click);
            RecentlyAddedButton_4.SoftButton_1.Click += new EventHandler(ViewReportButton_4_Click);
            RecentlyAddedButton_4.SoftButton_2.Click += new EventHandler(EditReportButton_4_Click);

            RecentlyAddedButton_1.SoftButton_1.MouseHover += new EventHandler(SoftButton_1_MouseHover);
            RecentlyAddedButton_2.SoftButton_1.MouseHover += new EventHandler(SoftButton_1_MouseHover);
            RecentlyAddedButton_3.SoftButton_1.MouseHover += new EventHandler(SoftButton_1_MouseHover);
            RecentlyAddedButton_4.SoftButton_1.MouseHover += new EventHandler(SoftButton_1_MouseHover);
            RecentlyAddedButton_1.SoftButton_2.MouseHover += new EventHandler(SoftButton_2_MouseHover);
            RecentlyAddedButton_2.SoftButton_2.MouseHover += new EventHandler(SoftButton_2_MouseHover);
            RecentlyAddedButton_3.SoftButton_2.MouseHover += new EventHandler(SoftButton_2_MouseHover);
            RecentlyAddedButton_4.SoftButton_2.MouseHover += new EventHandler(SoftButton_2_MouseHover);

            _connectionString = connectionString;
            this.Width = width;
            this.Height = height;

            _invoiceMode = invoiceMode;

            LoadRecentlyAddedRequisitionForms();
        }

        void SoftButton_1_MouseHover(object sender, EventArgs e)
        {
            HelpToolTip.Show("เปิดรายการ", (Button)sender);
        }

        void SoftButton_2_MouseHover(object sender, EventArgs e)
        {
            if(_invoiceMode)
                HelpToolTip.Show("สร้างใบกำกับภาษี/ใบส่งของ/ใบเสร็จรับเงินใหม่", (Button)sender);
            else
                HelpToolTip.Show("แก้ไขรายการ", (Button)sender);
        }

        void EditReportButton_1_Click(object sender, EventArgs e)
        {
            if (_invoiceMode)
                FormChangedEvent("INVOICE_ADD_3", new object[] { RecentlyAddedButton_1.IDLabel.Text });
            else
            {
                EditRequisitionAndInvoiceForm editRequisitionAndInvoiceForm = new EditRequisitionAndInvoiceForm(_connectionString,
                    2, Int32.Parse(RecentlyAddedButton_1.IDLabel.Text));
                editRequisitionAndInvoiceForm.EditFormClosedEvent += new EditFormClosedHandler(editRequisitionAndInvoiceForm_EditFormClosedEvent);
                editRequisitionAndInvoiceForm.ShowDialog();
            }
        }

        void ViewReportButton_1_Click(object sender, EventArgs e)
        {
            OpenReport(2, Int32.Parse(RecentlyAddedButton_1.IDLabel.Text));
        }

        void EditReportButton_2_Click(object sender, EventArgs e)
        {
            if (_invoiceMode)
                FormChangedEvent("INVOICE_ADD_3", new object[] { RecentlyAddedButton_2.IDLabel.Text });
            else
            {
                EditRequisitionAndInvoiceForm editRequisitionAndInvoiceForm = new EditRequisitionAndInvoiceForm(_connectionString,
                    2, Int32.Parse(RecentlyAddedButton_2.IDLabel.Text));
                editRequisitionAndInvoiceForm.EditFormClosedEvent += new EditFormClosedHandler(editRequisitionAndInvoiceForm_EditFormClosedEvent);
                editRequisitionAndInvoiceForm.ShowDialog();
            }
        }

        void ViewReportButton_2_Click(object sender, EventArgs e)
        {
            OpenReport(2, Int32.Parse(RecentlyAddedButton_2.IDLabel.Text));
        }

        void EditReportButton_3_Click(object sender, EventArgs e)
        {
            if (_invoiceMode)
                FormChangedEvent("INVOICE_ADD_3", new object[] { RecentlyAddedButton_3.IDLabel.Text });
            else
            {
                EditRequisitionAndInvoiceForm editRequisitionAndInvoiceForm = new EditRequisitionAndInvoiceForm(_connectionString,
                    2, Int32.Parse(RecentlyAddedButton_3.IDLabel.Text));
                editRequisitionAndInvoiceForm.EditFormClosedEvent += new EditFormClosedHandler(editRequisitionAndInvoiceForm_EditFormClosedEvent);
                editRequisitionAndInvoiceForm.ShowDialog();
            }
        }

        void ViewReportButton_3_Click(object sender, EventArgs e)
        {
            OpenReport(2, Int32.Parse(RecentlyAddedButton_3.IDLabel.Text));
        }

        void EditReportButton_4_Click(object sender, EventArgs e)
        {
            if (_invoiceMode)
                FormChangedEvent("INVOICE_ADD_3", new object[] { RecentlyAddedButton_4.IDLabel.Text });
            else
            {
                EditRequisitionAndInvoiceForm editRequisitionAndInvoiceForm = new EditRequisitionAndInvoiceForm(_connectionString,
                    2, Int32.Parse(RecentlyAddedButton_4.IDLabel.Text));
                editRequisitionAndInvoiceForm.EditFormClosedEvent += new EditFormClosedHandler(editRequisitionAndInvoiceForm_EditFormClosedEvent);
                editRequisitionAndInvoiceForm.ShowDialog();
            }
        }

        void ViewReportButton_4_Click(object sender, EventArgs e)
        {
            OpenReport(2, Int32.Parse(RecentlyAddedButton_4.IDLabel.Text));
        }

        void editRequisitionAndInvoiceForm_EditFormClosedEvent(int recordType)
        {
            if (recordType == 2)
                FormChangedEvent("REQUISITION_SELECTION", null);
        }

        private void OpenReport(int reportType, int orderID)
        {
            ShowPriceForm showPriceForm = new ShowPriceForm();
            ShowReportForm showReportForm;

            switch (showPriceForm.ShowDialog())
            {
                case DialogResult.OK:
                    showReportForm = new ShowReportForm(_connectionString);
                    showReportForm.setReportToShow(reportType, orderID, 
                        !showPriceForm.ShowPriceCheckBox.Checked, !showPriceForm.ShowWeightCheckBox.Checked, null);
                    showReportForm.LoadReport();
                    showReportForm.ShowDialog();
                    break;
                default:
                    break;
            }
        }

        private void LoadRecentlyAddedRequisitionForms()
        {
            try
            {
                _connection = new MySqlConnection(_connectionString);
                _connection.Open();

                string query;

                if(_invoiceMode)
                    query = "SELECT * from requisitionidcustomername WHERE IsInvoice = '0' ORDER BY RequisitionID DESC LIMIT 0, 4";
                else
                    query = "SELECT * from requisitionidcustomername ORDER BY RequisitionID DESC LIMIT 0, 4";

                _mySqlDataAdapter = new MySqlDataAdapter(query, _connection);

                DataTable dataTable = new DataTable();
                DataTable customerNameDataTable = new DataTable();

                _mySqlDataAdapter.Fill(dataTable);

                int itemsCount = 0;

                RecentlyAddedButton_1.Visible = false;
                RecentlyAddedButton_2.Visible = false;
                RecentlyAddedButton_3.Visible = false;
                RecentlyAddedButton_4.Visible = false;

                DateTime dateTime = DateTime.Now;

                for (int i = 0; i < dataTable.Rows.Count; i++)
                {
                    int ID;
                    switch (i)
                    {
                        case 0:
                            ID = Int32.Parse(dataTable.Rows[i][0].ToString());
                            RecentlyAddedButton_1.IDLabel.Text = ID.ToString("D6");
                            dateTime = DateTime.Parse(dataTable.Rows[i][2].ToString());
                            RecentlyAddedButton_1.DateCreatedLabel.Text =
                                ThaiWordsGenerator.ToThaiDate(dateTime);

                            query = "SELECT Name from customer WHERE CustomerID = \'" + dataTable.Rows[i][1].ToString() + "\'";
                            _mySqlDataAdapter = new MySqlDataAdapter(query, _connection);
                            customerNameDataTable.Clear();
                            _mySqlDataAdapter.Fill(customerNameDataTable);

                            RecentlyAddedButton_1.CompName.Text = customerNameDataTable.Rows[0][0].ToString();
                            RecentlyAddedButton_1.Visible = true;

                            if (dataTable.Rows[i][4].ToString() == "True")
                                RecentlyAddedButton_1.BackColor = Color.Bisque;
                            else
                                RecentlyAddedButton_1.BackColor = System.Drawing.SystemColors.Control;
                            break;
                        case 1:
                            ID = Int32.Parse(dataTable.Rows[i][0].ToString());
                            RecentlyAddedButton_2.IDLabel.Text = ID.ToString("D6");
                            dateTime = DateTime.Parse(dataTable.Rows[i][2].ToString());
                            RecentlyAddedButton_2.DateCreatedLabel.Text =
                                ThaiWordsGenerator.ToThaiDate(dateTime);

                            query = "SELECT Name from customer WHERE CustomerID = \'" + dataTable.Rows[i][1].ToString() + "\'";
                            _mySqlDataAdapter = new MySqlDataAdapter(query, _connection);
                            customerNameDataTable.Clear();
                            _mySqlDataAdapter.Fill(customerNameDataTable);

                            RecentlyAddedButton_2.CompName.Text = customerNameDataTable.Rows[0][0].ToString();
                            RecentlyAddedButton_2.Visible = true;

                            if (dataTable.Rows[i][4].ToString() == "True")
                                RecentlyAddedButton_2.BackColor = Color.Bisque;
                            else
                                RecentlyAddedButton_2.BackColor = System.Drawing.SystemColors.Control;
                            break;
                        case 2:
                            ID = Int32.Parse(dataTable.Rows[i][0].ToString());
                            RecentlyAddedButton_3.IDLabel.Text = ID.ToString("D6");
                            dateTime = DateTime.Parse(dataTable.Rows[i][2].ToString());
                            RecentlyAddedButton_3.DateCreatedLabel.Text =
                                ThaiWordsGenerator.ToThaiDate(dateTime);

                            query = "SELECT Name from customer WHERE CustomerID = \'" + dataTable.Rows[i][1].ToString() + "\'";
                            _mySqlDataAdapter = new MySqlDataAdapter(query, _connection);
                            customerNameDataTable.Clear();
                            _mySqlDataAdapter.Fill(customerNameDataTable);

                            RecentlyAddedButton_3.CompName.Text = customerNameDataTable.Rows[0][0].ToString();
                            RecentlyAddedButton_3.Visible = true;

                            if (dataTable.Rows[i][4].ToString() == "True")
                                RecentlyAddedButton_3.BackColor = Color.Bisque;
                            else
                                RecentlyAddedButton_3.BackColor = System.Drawing.SystemColors.Control;
                            break;
                        default:
                            ID = Int32.Parse(dataTable.Rows[i][0].ToString());
                            RecentlyAddedButton_4.IDLabel.Text = ID.ToString("D6");
                            dateTime = DateTime.Parse(dataTable.Rows[i][2].ToString());
                            RecentlyAddedButton_4.DateCreatedLabel.Text =
                                ThaiWordsGenerator.ToThaiDate(dateTime);

                            query = "SELECT Name from customer WHERE CustomerID = \'" + dataTable.Rows[i][1].ToString() + "\'";
                            _mySqlDataAdapter = new MySqlDataAdapter(query, _connection);
                            customerNameDataTable.Clear();
                            _mySqlDataAdapter.Fill(customerNameDataTable);

                            RecentlyAddedButton_4.CompName.Text = customerNameDataTable.Rows[0][0].ToString();
                            RecentlyAddedButton_4.Visible = true;

                            if (dataTable.Rows[i][4].ToString() == "True")
                                RecentlyAddedButton_4.BackColor = Color.Bisque;
                            else
                                RecentlyAddedButton_4.BackColor = System.Drawing.SystemColors.Control;
                            break;
                    }
                    itemsCount++;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                _connection.Close();
            }
        }

        private void SearchButton_Click(object sender, EventArgs e)
        {
            try
            {
                _connection = new MySqlConnection(_connectionString);
                _connection.Open();

                string fromDate = FromDateTimePicker.Value.ToString("yyyy-MM-dd") + " 00:00:00";
                string toDate = ToDateTimePicker.Value.ToString("yyyy-MM-dd") + " 23:59:59";

                string query;

                if(_invoiceMode)
                    query = "SELECT * from requisitionidcustomername WHERE IsInvoice = '0' AND Date BETWEEN \'" + 
                        fromDate + "\' AND \'" + toDate + "\' ORDER BY RequisitionID DESC";
                else
                    query = "SELECT * from requisitionidcustomername WHERE Date BETWEEN \'" +
                        fromDate + "\' AND \'" + toDate + "\' ORDER BY RequisitionID DESC";

                _mySqlDataAdapter = new MySqlDataAdapter(query, _connection);

                DataTable srcDataTable = new DataTable();
                _mySqlDataAdapter.Fill(srcDataTable);

                DataTable dstDataTable = new DataTable();
                if(!_invoiceMode)
                    dstDataTable.Columns.Add(COLUMN_1_NAME, typeof(bool));
                dstDataTable.Columns.Add(COLUMN_2_NAME);
                dstDataTable.Columns.Add(COLUMN_3_NAME);
                dstDataTable.Columns.Add(COLUMN_4_NAME);

                DataTable customerNameDataTable = new DataTable();

                foreach (DataRow dtRow in srcDataTable.Rows)
                {
                    DataRow newDtRow = dstDataTable.NewRow();
                    int idx = 0;

                    if (!_invoiceMode)
                    {
                        idx++;
                        newDtRow[0] = dtRow[4];
                    }
                    int ID = Int32.Parse(dtRow[0].ToString());
                    newDtRow[idx++] = ID.ToString("D6");

                    query = "SELECT Name from customer WHERE CustomerID = \'" + dtRow[1] + "\'";
                    _mySqlDataAdapter = new MySqlDataAdapter(query, _connection);
                    customerNameDataTable.Clear();
                    _mySqlDataAdapter.Fill(customerNameDataTable);

                    newDtRow[idx++] = customerNameDataTable.Rows[0][0].ToString();
                    DateTime dateTime = DateTime.Parse(dtRow[2].ToString());
                    newDtRow[idx] = ThaiWordsGenerator.ToThaiDate(dateTime);
                    
                    dstDataTable.Rows.Add(newDtRow);
                }

                if(_invoiceMode)
                    FormChangedEvent("INVOICE_ADD_2", new object[] 
                    { dstDataTable, ThaiWordsGenerator.ToThaiDate(FromDateTimePicker.Value), 
                        ThaiWordsGenerator.ToThaiDate(ToDateTimePicker.Value)});
                else
                    FormChangedEvent("REQUISITION_VIEW_2", new object[] 
                    { dstDataTable, ThaiWordsGenerator.ToThaiDate(FromDateTimePicker.Value), 
                        ThaiWordsGenerator.ToThaiDate(ToDateTimePicker.Value)});
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                _connection.Close();
            }
        }
    }
}
